package com.hexiang.book.dao.impl;

import com.hexiang.book.domain.Book;
import com.hexiang.book.dao.BookRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 使用NamedParameterJdbcTemplate来完成书籍数据库操作
 */
@Repository("namedParameterJdbcBookRepository")
public class NamedParameterJdbcBookRepository extends JdbcBookRepository {

    @Resource
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Resource
    private BookRowMapper bookRowMapper;

    @Override
    public int update(Book book) {
        return namedParameterJdbcTemplate.update(
                "update books set price = :price where id = :id",
                new BeanPropertySqlParameterSource(book));
    }

    @Override
    public Book findById(Long id) {
        return namedParameterJdbcTemplate.queryForObject("select * from books where id = :id", new MapSqlParameterSource("id", id), bookRowMapper
        );
    }

    @Override
    public List<Book> findByNameAndPrice(String name, BigDecimal price) {

        MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource();
        mapSqlParameterSource.addValue("name", "%" + name + "%");
        mapSqlParameterSource.addValue("price", price);

        return namedParameterJdbcTemplate.query("select * from books where name like :name and price <= :price", mapSqlParameterSource, bookRowMapper
        );
    }

}
